package com.zyw.weibo.ui.support;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.ToastWindow;
import cn.emagsoftware.ui.UIThread;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.util.DateUtilities;
import cn.emagsoftware.util.LogManager;

import com.zyw.weibo.Utilities;
import com.zyw.weibo.data.Weibo;
import com.zyw.weibo.data.remote.CodeException;
import com.zyw.weibo.data.remote.NetEngine;
import com.zyw.weibo.data.remote.NetOperatingManager;
import com.zyw.weibo.ui.R;

public class WeiboDataHolder extends DataHolder {
	
	protected String fromDesc = null;
	
	public WeiboDataHolder(Weibo wb,int asyncDataCount,String fromDesc){
		super(wb, asyncDataCount);
		this.fromDesc = fromDesc;
	}
	
	@Override
	public View onCreateView(Context arg0, int arg1, Object arg2) {
		// TODO Auto-generated method stub
		LinearLayout content = (LinearLayout)LayoutInflater.from(arg0).inflate(R.layout.main_index_list_item, null);
		ImageView head = (ImageView)content.findViewById(R.id.ivMainIndexHead);
		TextView title = (TextView)content.findViewById(R.id.tvMainIndexTitle);
		TextView time = (TextView)content.findViewById(R.id.tvMainIndexTime);
		TextView text = (TextView)content.findViewById(R.id.tvMainIndexText);
		ImageButton image = (ImageButton)content.findViewById(R.id.ibMainIndexImage);
		image.setFocusable(false);
		LinearLayout originalWrap = (LinearLayout)content.findViewById(R.id.llMainIndexOriginalWrap);
		TextView originalText = (TextView)content.findViewById(R.id.tvMainIndexOriginalText);
		ImageButton originalImage = (ImageButton)content.findViewById(R.id.ibMainIndexOriginalImage);
		originalImage.setFocusable(false);
		TextView from = (TextView)content.findViewById(R.id.tvMainIndexFrom);
		TextView redirect = (TextView)content.findViewById(R.id.tvMainIndexRedirect);
		TextView comment = (TextView)content.findViewById(R.id.tvMainIndexComment);
		ViewHolder viewHolder = new ViewHolder(head,title,time,text,image,originalWrap,originalText,originalImage,from,redirect,comment);
		content.setTag(viewHolder);
		onUpdateView(arg0,arg1,content,arg2,false);
		return content;
	}
	
	@Override
	public void onUpdateView(final Context arg0, int arg1, View arg2, Object arg3, boolean arg4) {
		// TODO Auto-generated method stub
		final Weibo wb = (Weibo)arg3;
		View[] views = ((ViewHolder)arg2.getTag()).getParams();
		ImageView head = (ImageView)views[0];
		TextView title = (TextView)views[1];
		title.getPaint().setFakeBoldText(true);
		TextView time = (TextView)views[2];
		TextView text = (TextView)views[3];
		ImageButton image = (ImageButton)views[4];
		LinearLayout originalWrap = (LinearLayout)views[5];
		TextView originalText = (TextView)views[6];
		ImageButton originalImage = (ImageButton)views[7];
		TextView from = (TextView)views[8];
		TextView redirect = (TextView)views[9];
		TextView comment = (TextView)views[10];
		if(TextUtils.isEmpty(wb.blogsender.selfpicture)) {
			head.setImageResource(R.drawable.main_index_list_item_defualthead);
		}else{
			Object asyncData = getAsyncData(0);
			if(asyncData == null) head.setImageResource(R.drawable.main_index_list_item_defualthead);
			else head.setImageDrawable((Drawable)asyncData);
		}
		title.setText(wb.blogsender.nickname);
		time.setText(DateUtilities.getFormatDate(DateUtilities.getParseDate(wb.blogtime, "yyyy-MM-dd HH:mm:ss"), "MM-dd HH:mm"));
		text.setText(Html.fromHtml(Utilities.convertWeiboToHtmlStyle(wb.bloguntreatedcontent),new Html.ImageGetter() {
			@Override
			public Drawable getDrawable(String source) {
				// TODO Auto-generated method stub
				int drawableId = arg0.getResources().getIdentifier(source, "drawable", arg0.getPackageName());
				Drawable d = arg0.getResources().getDrawable(drawableId);
				d.setBounds(0, -10, d.getIntrinsicWidth()+12,d.getIntrinsicHeight()+2);
				return d;
			}
		},null));
		if(wb.image == null){
			image.setVisibility(View.GONE);
		}else{
			image.setVisibility(View.VISIBLE);
			Object asyncData = null;
			if(TextUtils.isEmpty(wb.blogsender.selfpicture)) asyncData = getAsyncData(0);
			else asyncData = getAsyncData(1);
			if(asyncData == null) image.setImageResource(R.drawable.main_index_list_item_defualtimage);
			else image.setImageDrawable((Drawable)asyncData);
			image.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new UIThread(arg0){
						ToastWindow window = null;
						ProgressBar progress = null;
						ImageView image = null;
						Bitmap imageBit = null;
						@Override
						protected void onBeginUI(Context context) {
							window = new ToastWindow(context);
							window.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.generic_image_viewer_frame));
							window.setFocusable(true);
							RelativeLayout wrap = (RelativeLayout)LayoutInflater.from(context).inflate(R.layout.generic_image_viewer, null);
							window.setContentView(wrap);
							window.showCenter(((Activity)context).getWindow());
							window.setOnDismissListener(new PopupWindow.OnDismissListener() {
								@Override
								public void onDismiss() {
									// TODO Auto-generated method stub
									cancel();
									if(imageBit != null) imageBit.recycle();
								}
							});
							progress = (ProgressBar)wrap.findViewById(R.id.pbImageViewerProgress);
							image = (ImageView)wrap.findViewById(R.id.ivImageViewerImage);
						}
						@Override
						protected Object onRunNoUI(Context context) throws Exception {
							String picUrl = NetOperatingManager.URL_HOST + wb.image.imageurl;
							byte[] data = NetEngine.requestImage(context, picUrl);
							return BitmapFactory.decodeByteArray(data, 0, data.length);
						}
						@Override
						protected void onSuccessUI(Context context, Object result) {
							progress.setVisibility(View.GONE);
							Bitmap imageBitmap = (Bitmap)result;
							if(imageBitmap != null) {
								imageBit = imageBitmap;
								image.setImageBitmap(imageBit);
							}
						}
						@Override
						protected void onExceptionUI(Context context, Exception e) {
							LogManager.logE(WeiboDataHolder.class, "load image failed", e);
							window.setOnDismissListener(null);
							window.dismiss();
							String errorInfo = null;
							if(e instanceof CodeException) errorInfo = e.getMessage();
							else errorInfo = context.getString(R.string.generic_error);
							ToastManager.showLong(context, errorInfo);
						}
					}.start();
				}
			});
		}
		if(wb.originalblogid == null){
			originalWrap.setVisibility(View.GONE);
		}else{
			originalWrap.setVisibility(View.VISIBLE);
			originalText.setText(Html.fromHtml(Utilities.convertWeiboToHtmlStyle("@".concat(wb.originalblogid.blogsender.nickname).concat(":").concat(wb.originalblogid.bloguntreatedcontent)),new Html.ImageGetter() {
				@Override
				public Drawable getDrawable(String source) {
					// TODO Auto-generated method stub
					int drawableId = arg0.getResources().getIdentifier(source, "drawable", arg0.getPackageName());
					Drawable d = arg0.getResources().getDrawable(drawableId);
					d.setBounds(0, -10, d.getIntrinsicWidth()+12,d.getIntrinsicHeight()+2);
					return d;
				}
			},null));
			if(wb.originalblogid.image == null){
				originalImage.setVisibility(View.GONE);
			}else{
				originalImage.setVisibility(View.VISIBLE);
				Object asyncData = null;
				if(TextUtils.isEmpty(wb.blogsender.selfpicture)) {
					if(wb.image == null) asyncData = getAsyncData(0);
					else asyncData = getAsyncData(1);
				}else {
					if(wb.image == null) asyncData = getAsyncData(1);
					else asyncData = getAsyncData(2);
				}
				if(asyncData == null) originalImage.setImageResource(R.drawable.main_index_list_item_defualtimage);
				else originalImage.setImageDrawable((Drawable)asyncData);
				originalImage.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						new UIThread(arg0){
							ToastWindow window = null;
							ProgressBar progress = null;
							ImageView image = null;
							Bitmap imageBit = null;
							@Override
							protected void onBeginUI(Context context) {
								window = new ToastWindow(context);
								window.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.generic_image_viewer_frame));
								window.setFocusable(true);
								RelativeLayout wrap = (RelativeLayout)LayoutInflater.from(context).inflate(R.layout.generic_image_viewer, null);
								window.setContentView(wrap);
								window.showCenter(((Activity)context).getWindow());
								window.setOnDismissListener(new PopupWindow.OnDismissListener() {
									@Override
									public void onDismiss() {
										// TODO Auto-generated method stub
										cancel();
										if(imageBit != null) imageBit.recycle();
									}
								});
								progress = (ProgressBar)wrap.findViewById(R.id.pbImageViewerProgress);
								image = (ImageView)wrap.findViewById(R.id.ivImageViewerImage);
							}
							@Override
							protected Object onRunNoUI(Context context) throws Exception {
								String picUrl = NetOperatingManager.URL_HOST + wb.originalblogid.image.imageurl;
								byte[] data = NetEngine.requestImage(context, picUrl);
								return BitmapFactory.decodeByteArray(data, 0, data.length);
							}
							@Override
							protected void onSuccessUI(Context context, Object result) {
								progress.setVisibility(View.GONE);
								Bitmap imageBitmap = (Bitmap)result;	
								if(imageBitmap != null) {
									imageBit = imageBitmap;
									image.setImageBitmap(imageBit);
								}
							}
							@Override
							protected void onExceptionUI(Context context, Exception e) {
								LogManager.logE(WeiboDataHolder.class, "load original image failed", e);
								window.setOnDismissListener(null);
								window.dismiss();
								String errorInfo = null;
								if(e instanceof CodeException) errorInfo = e.getMessage();
								else errorInfo = context.getString(R.string.generic_error);
								ToastManager.showLong(context, errorInfo);
							}
						}.start();
					}
				});
			}
		}
		from.setText(fromDesc);
		redirect.setText(wb.forwardcount);
		comment.setText(wb.commentcount);
		
	}
	
}
